package com.base.param;

import lombok.Getter;
import net.sf.jsqlparser.expression.Alias;
import net.sf.jsqlparser.expression.Function;
import net.sf.jsqlparser.expression.JdbcParameter;
import net.sf.jsqlparser.schema.Column;
import net.sf.jsqlparser.statement.select.SelectItem;

import java.util.function.BiFunction;

public enum SqlFunctionKeyword {

    SUM("SUM", (selectItemParam, valueIsPlaceholder) -> getSelectItem(selectItemParam, valueIsPlaceholder)),
    COUNT("COUNT", (selectItemParam, valueIsPlaceholder) -> getSelectItem(selectItemParam, valueIsPlaceholder)),
    MAX("MAX", (selectItemParam, valueIsPlaceholder) -> getSelectItem(selectItemParam, valueIsPlaceholder)),
    AVG("AVG", (selectItemParam, valueIsPlaceholder) -> getSelectItem(selectItemParam, valueIsPlaceholder)),
    MIN("MIN", (selectItemParam, valueIsPlaceholder) -> getSelectItem(selectItemParam, valueIsPlaceholder)),
    DISTINCT_COUNT("DISTINCT_COUNT", (selectItemParam, valueIsPlaceholder) -> new SelectItem(new Function().withDistinct(true).withName("COUNT").withParameters(valueIsPlaceholder ? new JdbcParameter() : new Column(selectItemParam.getColumnCode()))).withAlias(new Alias(selectItemParam.getAlias()))),
    ;
    @Getter
    private final String keyword;
    @Getter
    private final BiFunction<SelectItemParam, Boolean, SelectItem> expressionFunction;


    SqlFunctionKeyword(String keyword, BiFunction<SelectItemParam, Boolean, SelectItem> expressionFunction) {
        this.keyword = keyword;
        this.expressionFunction = expressionFunction;
    }

    private static SelectItem getSelectItem(SelectItemParam selectItemParam, boolean valueIsPlaceholder) {
        return new SelectItem(new Function()
                .withName(selectItemParam.getFunctionName().name())
                .withParameters(valueIsPlaceholder ? new JdbcParameter() : new Column(selectItemParam.getColumnCode()))
                , new Alias(selectItemParam.getAlias()));

    }
}